import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

import { SortIndicator } from '../../../components/Helpers';
import Checkbox from '../../../components/Inputs/Checkbox';
import { dynamicSortMultiple, seo } from '../../../helpers';
import { useAppDispatch, useAppSelector } from '../../../hooks';
import LayoutBase from '../../../layouts/Base';
import { X4MapSectorInterface, getX4Map } from '../../../redux/x4/map';
import { displayDlcsInitial, formatDecimal, formatNumber, maps } from '../x4-helpers';
import './Resources.scss';

const RESOURCES = ['ore', 'silicon', 'ice', 'hydrogen', 'helium', 'methane', 'nividium', 'rawscrap'];

interface X4MapSectorInterfaceWithDlc extends X4MapSectorInterface {
  dlc: string;
}

export const X4ResourcesTable = () => {
  const dispatch = useAppDispatch();
  const { map } = useAppSelector((state) => state.x4Map);

  const [sort, setSort] = useState('name');
  const [showScore, setShowScore] = useState(true);
  const [showDetails, setShowDetails] = useState(false);
  const [sectors, setSectors] = useState<X4MapSectorInterfaceWithDlc[]>([]);
  const sortBy = (arg: string) => setSort(arg === sort ? `-${arg}` : arg);

  const [dlc, setDlc] = useState(displayDlcsInitial);

  useEffect(() => {
    const newSectors = [...sectors].sort(dynamicSortMultiple(sort, 'label'));

    if (
      sort.indexOf('ore') !== -1 ||
      sort.indexOf('silicon') !== -1 ||
      sort.indexOf('ice') !== -1 ||
      sort.indexOf('helium') !== -1 ||
      sort.indexOf('methane') !== -1 ||
      sort.indexOf('nividium') !== -1 ||
      sort.indexOf('rawscrap') !== -1 ||
      sort.indexOf('hydrogen') !== -1
    ) {
      newSectors.sort((a, b) => {
        let aRT = a.resourcesTotal ? a.resourcesTotal[sort.replace('-', '')] || 0 : 0;
        let bRT = b.resourcesTotal ? b.resourcesTotal[sort.replace('-', '')] || 0 : 0;
        return aRT < bRT ? 1 : bRT < aRT ? -1 : 0;
      });
    }

    if (sort.indexOf('sunlight') !== -1) {
      newSectors.sort((a, b) => {
        let aRT = a.sunlight ? a.sunlight || 0 : 0;
        let bRT = b.sunlight ? b.sunlight || 0 : 0;
        return aRT < bRT ? 1 : bRT < aRT ? -1 : 0;
      });
    }

    if (sort.indexOf('-') === 0) newSectors.reverse();

    setSectors(newSectors);
  }, [sort]);

  useEffect(() => {
    if (!map) dispatch(getX4Map());
    else {
      const orderedSectors: X4MapSectorInterfaceWithDlc[] = [];
      map.clusters.forEach((cluster) =>
        cluster.sectors.forEach((sector) => orderedSectors.push({ ...sector, dlc: cluster.dlc[0] }))
      );
      orderedSectors.sort(dynamicSortMultiple('label'));
      seo({
        title: 'X4 Foundations Resource Table',
        metaDescription: 'X4 Foundations, Split Vendetta and Cradle of Humanity resource table.',
        keywords: orderedSectors.map((sector) => sector.label),
      });
      setSectors(orderedSectors);
    }
  }, [dispatch, map]);

  return (
    <LayoutBase>
      <div className="x4-resources-table">
        <h1>X4 Resource table</h1>
        {map && (
          <React.Fragment>
            <div className="x4-resources-table__wrapper">
              <p className="no-mb">Short explanation: </p>
              <ul className="ul--packed mb-1 text--long">
                <li className="text--smaller">All values are normalized per hour.</li>
                <li className="text--smaller">
                  The number of specific resource is how much this sector / region can output in one hour.
                </li>
                <li className="text--smaller">
                  Regions will start with more resources available so you might get head start, but once they start
                  being heavily mined this metric kicks in.
                </li>
              </ul>
              <div className="x4-resources-table__controls">
                <div>
                  {Object.keys(dlc).map((dlcKey) => (
                    <Checkbox
                      label={maps.dlcs[dlcKey]}
                      name={maps.dlcs[dlcKey]}
                      checked={dlc[dlcKey]}
                      handleInputChange={() => setDlc({ ...dlc, [dlcKey]: !dlc[dlcKey] })}
                      labelClassName="text--xs"
                    />
                  ))}
                </div>
                <div>
                  <Checkbox
                    label="Show score"
                    name="showScore"
                    checked={showScore}
                    handleInputChange={(e) => setShowScore(e.target.checked)}
                    labelClassName="text--xs"
                  />
                  <Checkbox
                    label="Show details"
                    name="showDetails"
                    checked={showDetails}
                    handleInputChange={(e) => setShowDetails(e.target.checked)}
                    labelClassName="text--xs"
                  />
                </div>
                <Link to={'/x4/map'} className="link">
                  Go to interactive map
                </Link>
              </div>
              <table>
                <thead>
                  <tr>
                    <th onClick={() => sortBy('label')}>
                      System <SortIndicator attribute="label" activeAttribute={sort} />
                    </th>
                    <th className="x4-resources-table__fields">Field</th>
                    <th onClick={() => sortBy('ore')} className="number">
                      Ore <SortIndicator attribute="ore" activeAttribute={sort} />
                    </th>
                    <th onClick={() => sortBy('silicon')} className="number">
                      Sil. <SortIndicator attribute="silicon" activeAttribute={sort} />
                    </th>
                    <th onClick={() => sortBy('ice')} className="number">
                      Ice <SortIndicator attribute="ice" activeAttribute={sort} />
                    </th>
                    <th onClick={() => sortBy('hydrogen')} className="number">
                      Hydr. <SortIndicator attribute="hydrogen" activeAttribute={sort} />
                    </th>
                    <th onClick={() => sortBy('helium')} className="number">
                      Hel. <SortIndicator attribute="helium" activeAttribute={sort} />
                    </th>
                    <th onClick={() => sortBy('methane')} className="number">
                      Meth. <SortIndicator attribute="methane" activeAttribute={sort} />
                    </th>
                    <th onClick={() => sortBy('nividium')} className="number">
                      Nivi. <SortIndicator attribute="nividium" activeAttribute={sort} />
                    </th>
                    <th onClick={() => sortBy('rawscrap')} className="number">
                      Scrap <SortIndicator attribute="rawscrap" activeAttribute={sort} />
                    </th>
                    <th onClick={() => sortBy('sunlight')} className="number">
                      Sun <SortIndicator attribute="sunlight" activeAttribute={sort} />
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {sectors
                    .filter((sector) => dlc[sector.dlc])
                    .map((sector) => (
                      <React.Fragment key={sector.name}>
                        <tr>
                          <td title={sector.name}>
                            <p className="text--smaller text--bold">{sector.label}</p>
                            <p className="text--smaller">
                              <span
                                className="x4-resources-table__faction-tag"
                                style={{ background: sector.owner ? maps.colors[sector.owner].border : '#3333333' }}
                              />
                              {sector.owner ? maps.factions[sector.owner] : 'Neutral'}
                            </p>
                          </td>
                          {sector.resources ? (
                            <>
                              <td className="x4-resources-table__fields">
                                {showScore && <p className="text--smaller">Score</p>}
                                <p className="text--smaller text--bold">
                                  All {sector.resources ? sector.resources.length : 0} fields
                                </p>
                                {showDetails && <br />}
                                {showDetails &&
                                  sector.resources &&
                                  sector.resources.map((region, index) => (
                                    <p className="text--xs" key={index}>
                                      {region.name}
                                    </p>
                                  ))}
                              </td>

                              {['ore', 'silicon', 'ice', 'hydrogen', 'helium', 'methane', 'nividium', 'rawscrap'].map(
                                (resource) => (
                                  <td key={`${sector.name}${resource}`} className="number">
                                    {showScore &&
                                      sector.resourcePoints[resource] &&
                                      sector.resourcesTotal[resource] !== 0 && (
                                        <p
                                          className="x4-resources-table__resource-tag text--smaller"
                                          style={{ background: `${maps.resourceColors[resource]}` }}
                                        >
                                          {formatNumber(sector.resourcePoints[resource])}
                                        </p>
                                      )}
                                    {sector.resourcesTotal[resource] ? (
                                      <p
                                        title={`${resource[0].toUpperCase()}${resource
                                          .split('')
                                          .splice(1, resource.length)
                                          .join('')}`}
                                        className="text--smaller text--bold"
                                        style={{ borderBottom: `2px solid ${maps.resourceColors[resource]}` }}
                                      >
                                        {sector.resourcesTotal[resource] &&
                                          formatNumber(sector.resourcesTotal[resource] / 1000)}
                                        {sector.resourcesTotal[resource] ? 'k' : ''}
                                      </p>
                                    ) : (
                                      <p
                                        className="text--smaller text--bold"
                                        style={{ borderBottom: `2px solid transparent` }}
                                      >
                                        &nbsp;
                                      </p>
                                    )}
                                    {showDetails && <br />}
                                    {showDetails &&
                                      sector.resources &&
                                      sector.resources.map((region, index) => (
                                        <p className="text--xs" key={index}>
                                          {region.resourceQuantities[resource]
                                            ? formatNumber(region.resourceQuantities[resource])
                                            : ''}
                                          {region.resourceQuantities[resource] ? '' : '-'}
                                        </p>
                                      ))}
                                  </td>
                                )
                              )}
                            </>
                          ) : (
                            <td colSpan={9}></td>
                          )}
                          <td className="number">
                            <p className="text--smaller text--bold">{formatNumber(sector.sunlight * 100)}%</p>
                          </td>
                        </tr>
                      </React.Fragment>
                    ))}
                </tbody>
              </table>
            </div>
            <p className="text--long">
              Since some zones are huge, the maximum volume used in calculation is&nbsp;
              <span className="text--bold">limited to 200 km x 200 km x 100 km</span>. This seems like good enough
              estimation for relative calculations so that your ships don't have to fly too far out.
            </p>
            <p className="text--long">
              <span className="text--bold">What do the numbers mean?</span>
              <br />
              Each resource has a cap, this was done so that there can be a relative number which displays how good the
              system is for mining in comparison with other systems. On the map itself, the numbers only go to 99 since
              there is no room to display large numbers. Some regions in the game are enormous and if we put that as
              maximum, then most regions in game will scored as 0 and we can't see progress.
              <br />
              Around 100 point score is a point where this table and the map can show and differentiate smaller regions
              vs big ones. Everything over 10 on ore and silicon can support larger complexes and everything over 20 can
              support multilple ones. Once you reach about 50ish mark, you are more or less never going to run out of
              resources in those sectors.
            </p>
            <ul className="ul--packed text--long">
              <li>
                Full map data is available here:{' '}
                <a href="/api/x4/map" className="link" target="_blank">
                  Map data
                </a>
              </li>
              <li>
                Special thank you to&nbsp;
                <a
                  href="https://www.nexusmods.com/users/2663?tab=user+files"
                  className="link"
                  target="_blank"
                  rel="noreferrer"
                >
                  Allectus
                </a>
                , DeadAir and UniTrader from Egosoft discord for helping with calculations.
              </li>
            </ul>
          </React.Fragment>
        )}
      </div>
    </LayoutBase>
  );
};

export default X4ResourcesTable;
